package com.lingdiman.ocr.adapter;

import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.lingdiman.ocr.R;

import java.util.List;


public class IndicatorAdapter extends RecyclerView.Adapter<IndicatorAdapter.Holder> {

    private List<Integer> mDatas;

    private int selectPos;

    public void setData(List<Integer> data) {
        mDatas = data;
        notifyDataSetChanged();
    }

    public void setSelectPos(int pos) {
        selectPos = pos;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.indicator_item, null);
        //自定义view的宽度，控制一屏显示个数
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        int width = parent.getContext().getResources().getDisplayMetrics().widthPixels;
        int itemWidth = (width - dp2px(40 + mDatas.size() * 16)) / mDatas.size();
        params.width = itemWidth;
        params.height = dp2px(4);
        view.setLayoutParams(params);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        if (selectPos == position) {
            holder.mView.setBackgroundResource(R.drawable.select);
        } else {
            holder.mView.setBackgroundResource(R.drawable.unselector);
        }
    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    public static class Holder extends RecyclerView.ViewHolder {
        private TextView mView;

        public Holder(@NonNull View itemView) {
            super(itemView);
            mView = itemView.findViewById(R.id.indicator_view);
        }
    }

    private int dp2px(int dp) {
        float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (scale * dp + 0.5f);
    }
}
